package com.king.zxing.app.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.Toast;

import com.king.zxing.CaptureActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConserveJsonUtil extends CaptureActivity {
    private static String storePath = "/sdcard/Storagefactory/Json";
    private static boolean flag = false;
    private static boolean confirm = false;
    private static String strs;
    private static String str = "123" ;
    private static Activity mmActivity;
    private static String mmcontent;
    /**
     * / 判断字符串是否只有数字
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return !isNum.matches();
    }
    /**‘
     * 扫描二维码获取信息
     */
    public static void ScanQRcode(Activity mactivity,String result) {
        //判断开始
        String start = result.substring(0, 5);
        String end = result.substring((result.length() - 6));
        if (start.equals("start") && !flag) {
            strs = null;
            flag = true;
        }

        if (flag && isNumeric(result)){
            String str1 = result;
            if(!str.equals(str1)){//连续扫码时，直接弹出结果
                if (strs == null) {
                    if (start.equals("start") && end.equals("finish")){
                        strs = result.substring(6,result.length()-6);
                        flag = false;
                        Toast.makeText(mactivity,"扫码结束！",Toast.LENGTH_SHORT).show();
                        ConserveJsonUtil.saveToSDCard(mactivity,strs);
                    }else{
                        strs = result.substring(6);
                        Toast.makeText(mactivity,"开始！",Toast.LENGTH_SHORT).show();
                    }
                }else if (end.equals("finish")){   //判断结束
                    strs+=result.substring(0,result.length() - 6);
                    flag = false;
                    Toast.makeText(mactivity,"扫码结束！",Toast.LENGTH_SHORT).show();
                    //保存二维码内容成一个Json文件
                    ConserveJsonUtil.saveToSDCard(mactivity,strs);
                }else{
                    strs+=result;
                    Toast.makeText(mactivity,"成功！",Toast.LENGTH_SHORT).show();
                }
                str = result;
            }
        }
        /*999
        //延时扫码
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 保存json到本地
     */
    public static void saveToSDCard(Activity mActivity, String content) {
        mmActivity = mActivity;
        mmcontent = content;
        if (content.length() <= 0) {
            Toast.makeText(mActivity, "内容为空！", Toast.LENGTH_LONG).show();
            return;
        }
        int sum = content.indexOf("@");
        String filename = content.substring(sum+1);
//        System.out.println(content);
        content = content.substring(0,sum);
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            if (!appDir.mkdirs()) {
                Log.e("--Method--", "copyFolder: cannot create directory.");
                return;
            }
        }
        File[] files=appDir.listFiles();
        if (files == null){
            Toast.makeText(mActivity, "此目录为空！", Toast.LENGTH_LONG).show();
        }
        for(int i =0;i<files.length;i++){
            if ((filename + ".json").equals(files[i].getName())){
                if (confirm){
                    files[i].delete();
                    confirm = false;
                }else{
                    ConserveJsonUtil.fileiEexist(mActivity);
                    Toast.makeText(mActivity, "已存在该控件！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
        try {
            File file = new File(appDir, filename+".json");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
            Toast.makeText(mActivity,"保存成功",Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mActivity,"保存失败",Toast.LENGTH_SHORT).show();
        }

    }
    private static DialogInterface.OnClickListener click1= (arg0, arg1) -> {
        confirm = true;
        ConserveJsonUtil.saveToSDCard(mmActivity,mmcontent);
    };
    private static DialogInterface.OnClickListener click2= (arg0, arg1) ->{ return;};

    public static void fileiEexist(Activity mActivity) {
        confirm = false;
        AlertDialog.Builder alertdialogbuilder=new AlertDialog.Builder(mActivity);
        alertdialogbuilder.setMessage("您确认要覆盖数据？");
        alertdialogbuilder.setPositiveButton("确定", click1);
        alertdialogbuilder.setNegativeButton("取消", click2);
        AlertDialog alertdialog1=alertdialogbuilder.create();
        alertdialog1.show();
    }

}
